package com.liziyi0914.morearmor;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.liziyi0914.morearmor.data.DataManager;
import lombok.NonNull;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.Item;
import net.minecraft.tag.Tag;
import net.minecraft.util.registry.Registry;

import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.function.Predicate;

public class Utils {

    public static final int ARMOR_TYPE_HELMET = 0;
    public static final int ARMOR_TYPE_CHESTPLATE = 1;
    public static final int ARMOR_TYPE_LEGGINGS = 2;
    public static final int ARMOR_TYPE_BOOTS = 3;

    private static final String[][] ARMOR_RECIPE = new String[][]{
            new String[]{"XXX", "X X"},
            new String[]{"X X", "XXX", "XXX"},
            new String[]{"XXX", "X X", "X X"},
            new String[]{"X X", "X X"}
    };
    private static final String[] ARMOR_NAME = new String[]{
            "helmet",
            "chestplate",
            "leggings",
            "boots"
    };

    private static final Gson gson = new Gson();

    public static JsonElement autoRecipe(int type, Item item) {
        String id = Registry.ITEM.getId(item).getPath();
        JsonObject json = new JsonObject();
        json.addProperty("type", "minecraft:crafting_shaped");

        JsonArray jsonArray = new JsonArray();
        for (String s : ARMOR_RECIPE[type]) {
            jsonArray.add(s);
        }
        json.add("pattern", jsonArray);

        JsonObject individualKey = new JsonObject();
        JsonObject keyList = new JsonObject();
        individualKey.addProperty("item", "minecraft:" + id);
        keyList.add("X", individualKey);
        json.add("key", keyList);

        JsonObject result = new JsonObject();
        result.addProperty("item", MoreArmorMod.MODID + ":" + id + "_" + ARMOR_NAME[type]);
        result.addProperty("count", 1);
        json.add("result", result);
        return json;
    }

    public static Gson gson() {
        return gson;
    }

    public static Predicate<LivingEntity> hasItemArmor(Item item) {
        return entity -> DataManager.get(entity).stream().anyMatch(e -> Objects.nonNull(e) && e.getItem() == item);
    }

    public static Predicate<LivingEntity> hasItemTagArmor(Tag<Item> tag) {
        return entity -> DataManager.get(entity).stream().anyMatch(e -> tag.contains(e.getItem()));
    }
    public static Predicate<Item> hasItem(Tag<Item> tag) {
        return tag::contains;
    }

    private static final Random random = new Random();

    public static <T> T randomGet(@NonNull List<T> list) {
        if (list.isEmpty()) throw new ArrayIndexOutOfBoundsException("Empty List");
        return list.get(random.nextInt(list.size()));
    }
}
